<template>
    <basic-container>
        <avue-crud :data="data" :option="option" :table-loading="loading" :page="page" @refresh-change="refreshChange"
                   @search-change="searchChange"
                   @search-reset="searchReset" @current-change="currentChange"
                   @size-change="sizeChange" @on-load="onLoad" @row-del="rowDel">
            <!-- 自定义添加搜索条件  按日期搜索  -->
            <template slot-scope="scope" slot="search">
                <el-col :md="8" :xs="10">
                    <el-form-item label="有效期">
                        <el-date-picker v-model="acTime" type="daterange" range-separator="至" size="mini"
                                        start-placeholder="开始日期" end-placeholder="结束日期" align="right"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </template>
            <template slot-scope="scope" slot="menuLeft">
                <el-button v-if="!userType" type="primary" size="mini" @click="handleAdd">
                    新增
                </el-button>
            </template>
            <template slot-scope="{row}" slot="menu">
                <el-button v-if="row.goodsStatus==0 && userOrganizationId<row.organizationId && !row.isUtil" type="text" size="mini"
                           @click="handlePass(row,1)">
                    通过
                </el-button>
                <el-button v-if="row.goodsStatus==0 && userOrganizationId<row.organizationId && !row.isUtil" type="text" size="mini"
                           @click="handlePass(row,-1)">
                    拒绝
                </el-button>
                <el-button type="text" size="mini" @click="handleEdit(row)">
                    编辑
                </el-button>
            </template>
            <template slot-scope="{row}" slot="photoUrl">
                <el-image :src="row.photoUrl" style="width: 50px;height: 50px"></el-image>
            </template>
        </avue-crud>

        <!-- 新增 -->
        <el-dialog :close-on-click-modal="false" :title="titleBan" :visible.sync="dialogVisible" width="60%"
                   :before-close="closeDialog">
            <el-form :model="addForm" :rules="addrules" ref="addForm" label-width="140px">
                <el-form-item label="商品" prop="homeGoodsId">
                    <div>
                        <el-col :span="12">
                            <el-form-item>
                                <el-input v-model="addForm.goodsName" size="mini" readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col style="width: 40px;height: 40px;overflow: hidden;margin-left: 15px;background: #f5f6f7;text-align: center;">
                            <div class="demo-image__preview">
                                <el-image :src="addForm.goodsMainPhotoUrl"
                                          width="40"
                                          height="40"
                                >
                                    <div slot="error" class="image-slot">
                                        <i class="el-icon-picture-outline" style="font-size: 18px"></i>
                                    </div>
                                </el-image>
                            </div>
                        </el-col>
                        <el-col style="width: 90px;margin-left: 15px;">
                            <el-form-item prop="adAccUrl">
                                <el-button icon="el-icon-search" type="primary" size="mini" @click="chooseGoods">浏览
                                </el-button>
                            </el-form-item>
                        </el-col>
                    </div>
                </el-form-item>
                <el-form-item v-if="dialogVisible" label="开始时间" prop="beginTime">
                    <el-date-picker :readonly="isView" @change="checkStartTime" v-model="addForm.beginTime"
                                    :picker-options="pickerOption" default-time="00:00:00"
                                    value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期" size="mini">
                    </el-date-picker>
                </el-form-item>
                <el-form-item v-if="dialogVisible" label="结束时间" prop="endTime">
                    <el-date-picker size="mini" :readonly="isView" @change="getAddTime" v-model="addForm.endTime"
                                    :picker-options="pickerOption" default-time="23:59:59"
                                    type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitAdvert('addForm')" size="mini" :loading="loadBtn"
                >确 定</el-button>
				<el-button @click="closeDialog" size="mini">取 消</el-button>
			</span>
        </el-dialog>
        <!-- 选择商品 -->
        <el-drawer :wrapperClosable="true" :visible.sync="drawerGoods" :before-close="closeDrawer"
                   custom-class="drawerClass" :with-header="false" size="60%">
            <div class="demo-drawer__header">
                <div class="drawerHeader"><strong>商品列表</strong></div>
            </div>
            <div class="demo-drawer__content">
                <avue-crud
                        ref="goodsCrud"
                        :data="sellerGoodsList"
                        :option="sellerGoodsOption"
                        v-model="sellerGoods"
                        :table-loading="sellerGoodsloading"
                        :page="sellerGoodsPage"
                        @refresh-change="refreshSellerGoodsChange"
                        @search-change="searchSellerGoodsChange"
                        @search-reset="searchSellerGoodsReset"
                        @current-change="currentSellerGoodsChange"
                        @size-change="sizeSellerGoodsChange"
                        @on-load="onSellerGoodsLoad"
                >
                    <template slot="search">
                        <el-col :md="10" :xs="10">
                            <el-form-item label="商品分类" style="display: inline-block;width: 80%;">
                                <el-cascader :props="classOptions" v-model="goodsClassId" :options="chooseProductOption" size="mini" @change="handleChange"></el-cascader>
                            </el-form-item>
                        </el-col>
                    </template>
                    <template slot-scope="{ row }" slot="goodsMainPhotoUrl">
                        <img :src="row.goodsMainPhotoUrl" style="width:50px;height:50px;"/>
                    </template>
                    <template slot-scope="scope" slot="menu">
                        <el-button size="mini" type="text" @click="addGoods(scope.row)">添加</el-button>
                    </template>
                </avue-crud>
            </div>
        </el-drawer>

        <!--        商品冲突提示框-->
        <el-dialog
                title=""
                :visible.sync="dialogVisibleAd"
                width="80%">
            <span style="padding-bottom: 30px;font-size: 20px;font-weight: 600;">该商品展示的时间与以下商品的时间冲突，如果覆盖，请选择覆盖的商品</span>
            <el-radio-group v-model="chooseAdIndex" @change="changeChooseAd">
                <el-row style="padding: 10px" v-for="(item,index) in conflictAdList" :key="item.id">
                    <el-radio :label="index">{{item.goodsName}}
                        冲突的时间:{{item.beginTime}}到{{item.endTime}}
                    </el-radio>
                </el-row>
            </el-radio-group>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelConfigAd">取 消</el-button>
                <el-button type="primary" @click="sureConflictAd" :loading="chooseLoading">确 定</el-button>
            </span>
        </el-dialog>
    </basic-container>
</template>
<script>
    import {getList, getGoodsList, addItem, editItem, remove} from '@/api/base/operations/recommendProducts';
    import {mapGetters} from "vuex";
import { getClassList} from '@/api/base/goods/goods';

    export default {
        data() {
            return {
                classOptions: {
                    label: 'className',
                    value: 'id',
                    children: 'childrenNodes',
                },
                data:[],
                userOrganizationId: '',
                userType: '', // 当前用户的组织Id
                conflictAdList: [],
                chooseLoading: false,
                chooseAdIndex: '',
                dialogVisibleAd: false,
                pickerOption: {
                    disabledDate(time) {
                        return time.getTime() + 3600 * 1000 * 24 * 1 < Date.now();
                    }
                },
                chooseGood: {},
                titleBan: '新增',
                loadBtn: false,
                isView: false,
                addrules: {
                    beginTime: [{
                        required: true,
                        message: "请选择开始时间",
                        trigger: "blur"
                    }],
                    endTime: [{
                        required: true,
                        message: "请选择结束时间",
                        trigger: "blur"
                    }],
                },
                dialogVisible: false, // 新增框的显隐
                acTime: [],
                loading: true,
                option: {
                    size: 'mini',
                    delBtn: true,
                    border:true,
                    page: true,
                    align: 'center',
                    menuAlign: 'center',
                    addBtn: false,
                    dialogType: 'dialog',
                    editBtn: false,
                    column: [
                        {
                            label: '商品名称',
                            prop: 'goodsName',
                            required: true,
                            search: true,
                            searchLabelWidth: 100,
                            searchSpan: 5,
                            width: 150,
                        },
                        {
                            label: '商品图片',
                            prop: 'photoUrl',
                            slot: true,
                        }, {
                            width: 160,
                            type: "datetime",
                            label: "开始时间",
                            prop: "beginTime",
                            select: true,
                            format: "yyyy-MM-dd HH:mm:ss",
                            valueFormat: "yyyy-MM-dd HH:mm:ss",
                            rules: [{
                                required: true,
                                message: "请输入商品开始时间--不可售卖可用",
                                trigger: "blur"
                            }]
                        },
                        {
                            width: 160,
                            type: "datetime",
                            label: "结束时间",
                            select: true,
                            prop: "endTime",
                            format: "yyyy-MM-dd HH:mm:ss",
                            valueFormat: "yyyy-MM-dd HH:mm:ss",
                            rules: [{
                                required: true,
                                message: "请输入商品结束时间--非售卖商品可用",
                                trigger: "blur"
                            }]
                        }, {
                            label: "区域",
                            type: "tree",
                            prop: "organizationName",
                            defaultExpandAll: false,
                            disabled: false,
                            dicUrl: '/base/organization/listTreeBylevelM',
                            props: {
                                label: 'name',
                                value: 'id',
                                children: 'childrenNodes'
                            },
                            rules: [{
                                required: true,
                                message: "请选择区域",
                                trigger: "blur",
                            }]
                        }, {
                            label: '审核状态',
                            prop: 'goodsStatus',
                            type: 'select',
                            search: true,
                            searchLabelWidth: 100,
                            searchSpan: 5,
                            dicData: [{value: 0, label: '未审核'}, {value: 1, label: '审核通过'}, {value: -1, label: '审核拒绝'}]
                        }
                    ]
                },
                arrList: [],
                drawerGoods: false,
                addForm: {},
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                index: 0,
                sellerGoodsList: [],
                sellerGoods: {},
                sellerGoodsloading: false,
                sellerGoodsQuery: {},
                sellerGoodsPage: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                sellerGoodsOption: {
                    header: false,
                    selection: false,
                    menu: true,
                    search: true,
                    // searchMenuSpan: 6,
                    editBtn: false,
                    delBtn: false,
                    border: true,
                    align: 'center',
                    menuWidth: 200,
                    column: [
                        {
                            label: '商品图片',
                            prop: 'goodsMainPhotoUrl',
                            width: 100,
                            slot: true
                        },
                        {
                            label: '商品名称',
                            prop: 'goodsName',
                            searchSpan: 8,
                            align: 'left',
                            search: true
                        },
                        {
                            label: '指定分类',
                            prop: 'goodsClassId',
                            type: 'select',
                            readonly:false,
                            dicUrl: '/base/goodsClass/listManage?classLevel=2',
                            searchSpan: 8,
                            width: 80,
                            props: {
                                label: 'className',
                                value: 'id'
                            },

                        },
                        {
                            label: '总库存',
                            prop: 'stock',
                            width: 70,
                            span: 24
                        },
                        {
                            label: '商城售价',
                            prop: 'showPrice',
                            width: 120,
                            span: 24
                        }
                    ]
                },
                query: {},
                chooseProductOption:[],
                goodsClassId:''
            };
        },
        computed: {
            ...mapGetters(['userInfo']),
        },
        created() {
            getClassList().then(res => {
                if (res.data.code == 200) {
                    res.data.data.forEach(item=>{
                        if(item.childrenNodes.length>0){
                            item.childrenNodes.forEach(it=>{
                                if(it.childrenNodes.length>0){
                                    it.childrenNodes.forEach(i=>{
                                        if(i.childrenNodes.length==0){
                                            delete i.childrenNodes
                                        }
                                    })
                                }else{
                                    delete it.childrenNodes
                                }
                            })
                        }else{
                            delete item.childrenNodes
                        }
                    })
                    this.chooseProductOption = res.data.data;
                    console.log(this.chooseProductOption)
                }
            });
            this.userOrganizationId = this.userInfo.organizationId // 获取用户的区域Id
            this.userType = this.userInfo.roleIds.includes(1) || this.userInfo.roleIds.includes(8) // 获取用户的区域Id
            console.log('user身份', this.userType)
        },
        methods: {
            handleEdit(row) {
                this.titleBan = '编辑'
                this.dialogVisible = true
                this.addForm = JSON.parse(JSON.stringify(row))
                this.chooseGood = row
                this.chooseGood.goodsMainPhotoUrl = row.photoUrl
                this.addForm.goodsMainPhotoUrl = row.photoUrl
                console.log('row111', this.addForm)
            },
            changeChooseAd(value) { // 冲突商品单选框选择
                console.log('value', value)
                this.chooseAdIndex = value
            },
            // 确定覆盖的商品
            sureConflictAd() {
                console.log('chooseIndex',this.chooseAdIndex)
                if(this.chooseAdIndex.toString() =='') {
                    this.$message({
                        type: "error",
                        message: "请选择覆盖的商品!"
                    });
                    return
                }
                this.chooseLoading = true
                console.log('this.addForm', this.addForm)
                if (this.addForm.id) {
                    this.addForm.originalId = this.conflictAdList[this.chooseAdIndex].id
                    this.addForm.type = this.conflictAdList[this.chooseAdIndex].type
                    editItem(this.addForm).then((res) => {
                        if (res.data.code == 200) {
                            this.loadBtn = false
                            this.$message({
                                type: "success",
                                message: "编辑商品成功!"
                            });
                            this.dialogVisible = false;
                            this.dialogVisibleAd = false
                            this.chooseLoading = false
                            this.loadBtn = false
                            this.onLoad(this.page, this.query)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.data.message
                            });
                        }
                        this.chooseLoading = false
                        this.loadBtn = false
                    })
                    this.chooseAdIndex = ''
                } else {
                    console.log('冲突')
                    console.log(this.addForm, 'chongchongc')
                    this.addForm.originalId = this.conflictAdList[this.chooseAdIndex].id
                    this.addForm.type = this.conflictAdList[this.chooseAdIndex].type
                    editItem(this.addForm).then((res) => {
                        if (res.data.code == 200) {
                            this.loadBtn = false
                            this.$message({
                                type: "success",
                                message: "编辑商品成功!"
                            });
                            this.chooseGood = ''
                            this.$refs.addForm.resetFields();
                            this.$refs.addForm.clearValidate();
                            this.dialogVisible = false;
                            this.dialogVisibleAd = false
                            this.chooseLoading = false
                            this.loadBtn = false
                            this.onLoad(this.page, this.query)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.data.message
                            });
                            this.chooseLoading = false
                            this.loadBtn = false
                        }
                    })
                    this.closeDialog()
                    this.chooseAdIndex = ''
                }
            },
            cancelConfigAd() { //拒绝选择覆盖商品
                this.dialogVisibleAd = false
                this.chooseAdIndex = ''
                this.$message({
                    type: "warning",
                    message: "建议修改新增的商品时间!"
                });
            },
            handleAdd() {
                // this.closeDialog()
                this.titleBan = '新增'
                this.chooseGood = ''
                this.addForm = {}
                this.dialogVisible = true
            },
            editItemFn(obj, state) {
                editItem(obj).then(res => {
                    if (res.data.code == 200) {
                        if (state == 1) {
                            this.$message({
                                type: "success",
                                message: "审核通过!"
                            });
                        } else if (state == -1) {
                            this.$message({
                                type: "success",
                                message: "审核拒绝!"
                            });
                        }
                    }
                })
            },
            // 通过
            handlePass(row, state) {
                console.log('row', row)
                let obj = row
                obj.goodsStatus = state
                this.editItemFn(obj, state)
            },
            chooseGoods() {
                this.drawerGoods = true
            },
            checkStartTime() {
                if (this.addForm.endTime != null && this.addForm.endTime != undefined && this.addForm.endTime != "") {
                    if (this.addForm.beginTime >= this.addForm.endTime) {
                        this.$message({
                            type: "error",
                            message: "开始时间不能大于等于结束时间"
                        });
                        this.addForm.beginTime = '';
                        return;
                    }
                }
                if (this.addForm.beginTime <= new Date().getTime()) {
                    this.$message({
                        type: "error",
                        message: "开始时间不能小于等于当前时间"
                    });
                    this.addForm.beginTime = ''
                }
            },
            getAddTime() {
                if (this.addForm.beginTime >= this.addForm.endTime) {
                    this.$message({
                        type: "error",
                        message: "结束时间不能小于等于开始时间"
                    });
                    this.addForm.endTime = ''
                }
            },
            //新增关闭
            closeDialog(done) {
                console.log('关闭回调')
                this.chooseGood = ''
                this.addForm = {}

                this.$refs.addForm.resetFields();
                this.$refs.addForm.clearValidate();
                this.loadBtn = false
                this.dialogVisible = false
                this.onLoad(this.page)
                if (done) {
                    done
                }
            },
            searchReset() {
                this.query = {};
                this.acTime = []
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.page.currentPage = 1
                params.beginTime = this.acTime[0]
                params.endTime = this.acTime[1]
                console.log(params)
                this.query = params;
                console.log(this.query)
                this.onLoad(this.page, params, done);
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page);
            },
            //点击满赠商品输入框，打开选择商品的列表
            changeGoods(index) {
                console.log('index', index);
                this.index = index;
                this.drawerGoods = true;
            },
            onLoad(page, params = {}, done) {
                this.loading = true;
                getList(
                    page.currentPage,
                    page.pageSize,
                    Object.assign(params, this.query)
                ).then(res => {
                    if (done) {
                        done();
                    }
                    this.loading = false;
                    this.page.total = res.data.count;
                    if(res.data.data.length<1 && this.page.currentPage>1) {
                        this.page.currentPage -=1
                        this.onLoad(this.page)
                        return
                    }
                    if(this.userType) {
                        res.data.data.forEach(item=>{
                            let arr = item.area.split(',')
                            item.isUtil = false
                            if (arr.length>2) {
                                item.isUtil = true
                            }
                        })
                        this.data = res.data.data;
                    }else {
                        res.data.data.forEach(item=>{
                            item.isUtil = false
                        })
                        this.data = res.data.data;
                    }
                    console.log('this.data',this.data)


                });
            },
            // 提交按钮
            submitAdvert() {
                if (!this.addForm.homeGoodsId) {
                    this.$message({
                        type: "error",
                        message: "请选择商品!"
                    });
                    return
                }

                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        this.loadBtn = true
                        if (this.addForm.id) {
                            this.addForm.goodsStatus = 0
                            console.log('this.addForm', this.addForm)
                            editItem(this.addForm).then(res => {
                                if (res.data.code == 200) {
                                    let key = res.data.data.length
                                    if (key == 0) { //没有商品冲突,直接新增商品成功
                                        this.loadBtn = false
                                        this.$message({
                                            type: "success",
                                            message: "编辑商品成功!"
                                        });
                                        this.chooseGood = ''
                                        this.$refs.addForm.resetFields();
                                        this.$refs.addForm.clearValidate();
                                        this.addForm = {}
                                        this.dialogVisible = false;
                                        this.onLoad(this.page, this.query)
                                        this.loadBtn = false
                                        this.closeDialog()
                                    } else {
                                        this.dialogVisibleAd = true
                                        this.chooseAdIndex = ''
                                        this.conflictAdList = res.data.data.slice(0, 3) // 冲突商品的列表
                                    }
                                    this.loadBtn = false
                                }
                            })

                        } else {
                            console.log('this.addForm', this.addForm)
                            addItem(this.addForm).then(res => {
                                if (res.data.code == 200) {
                                    let key = res.data.data.length
                                    if (key == 0) { //没有商品冲突,直接新增商品成功
                                        this.loadBtn = false
                                        this.$message({
                                            type: "success",
                                            message: "新增商品成功!"
                                        });
                                        this.chooseGood = ''
                                        this.$refs.addForm.resetFields();
                                        this.$refs.addForm.clearValidate();
                                        this.chooiseAd = ''
                                        this.dialogVisible = false;
                                        this.onLoad(this.page, this.query)
                                        this.addForm = {}
                                        this.loadBtn = false
                                    } else {
                                        this.dialogVisibleAd = true
                                        this.chooseAdIndex = ''
                                        this.conflictAdList = res.data.data // 冲突商品的列表
                                    }
                                    this.loadBtn = false
                                }
                            })
                        }

                    }
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id).then(res => {
                            if (res.data.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功'
                                })
                                this.onLoad(this.page, this.query)
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.data.data.message
                                })
                            }
                        })
                            .catch(() => {
                                this.$message({
                                    type: 'info',
                                    message: '已取消删除'
                                })
                            })
                    })
            },
            addGoods(good) {
                console.log(good);
                console.log(this.index);
                this.addForm.goodsMainPhotoUrl = good.goodsMainPhotoUrl
                this.addForm.goodsName = good.goodsName
                this.addForm.homeGoodsId = good.id
                this.chooseGood = good
                this.closeDrawer()
            },
			handleChange(value) {
				this.goodsClassId=value[value.length-1]
			},
            // 新增时 选择赠品 商品表格方法
            searchSellerGoodsReset() {
                this.sellerGoodsQuery = {};
                this.goodsClassId=''
                this.onSellerGoodsLoad(this.sellerGoodsPage);
            },
            searchSellerGoodsChange(params) {
                this.sellerGoodsQuery = params;
                this.sellerGoodsQuery.goodsClassId = this.goodsClassId;
                this.sellerGoodsPage.currentPage = 1;
                this.onSellerGoodsLoad(this.sellerGoodsPage, params);
            },

            currentSellerGoodsChange(currentPage) {
                this.sellerGoodsPage.currentPage = currentPage;
                this.onSellerGoodsLoad(this.sellerGoodsPage);
            },
            sizeSellerGoodsChange(pageSize) {
                this.sellerGoodsPage.pageSize = pageSize;
                this.onSellerGoodsLoad(this.sellerGoodsPage);
            },
            refreshSellerGoodsChange() {
                this.currentSellerGoodsChange(1);
                this.onSellerGoodsLoad(this.sellerGoodsPage);
            },
            onSellerGoodsLoad(sellerGoodsPage, params = {}) {
                params.goodsStatus = 0;
                //params.goodsRecommend=0;
                this.sellerGoodsloading = true;
                getGoodsList(sellerGoodsPage.currentPage, sellerGoodsPage.pageSize, Object.assign(params, this.sellerGoodsQuery)).then(res => {
                    this.sellerGoodsloading = false;
                    const data = res.data;
                    this.sellerGoodsPage.total = data.count;
                    data.data.forEach(item => {
                        item.showPrice = item.showPrice;
                    });
                    this.sellerGoodsList = data.data;
                });
            },
            closeDrawer() {
                this.$refs.goodsCrud.searchReset()
                this.drawerGoods = false;
                this.sellerGoodsQuery.goodsName = '';
                this.goodsClassId = '';

            }
        }
    };
</script>
<style scoped>
    .drawerHeader {
        font-size: 20px;
        padding: 5px 20px;
    }

    .demo-drawer__content {
        padding: 50px;
    }

    .upload {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }
</style>
